<template>
  <el-card class="w-full">
    <div class="w-full main h-[calc(100%-29px)]">
      <div class="w-full">
        <div v-if="queryShow" class="mb-[10px] w-full search-form">
          <el-form :inline="true" :model="queryForm.data" label-width="0px">
            <el-form-item>
              <el-input
                v-model="queryForm.data.blurry"
                clearable
                placeholder="请输入你要搜索的内容"
              />
            </el-form-item>
            <el-form-item>
              <el-date-picker
                v-model="queryForm.data.createTime"
                type="datetimerange"
                range-separator=":"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item class="ml-[10px]">
              <el-button type="primary" :icon="Search" @click="search"
                >搜索</el-button
              >
              <el-button :icon="RefreshLeft" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div class="w-full">
          <div class="w-full flex justify-between">
            <div class="buttons flex align-center">
              <el-button type="danger" :icon="Delete" @click="delSelect"
                >清空</el-button
              >
              <el-button type="warning" :icon="Download" @click="exportData"
                >导出</el-button
              >
            </div>
            <div class="settings">
              <el-button-group class="ml-4">
                <el-button
                  type="primary"
                  :icon="Search"
                  @click="queryShow = !queryShow"
                />
                <el-button
                  type="primary"
                  :icon="RefreshLeft"
                  @click="getList"
                />
                <el-popover placement="bottom" :width="200" trigger="click">
                  <template #reference>
                    <el-button type="primary" :icon="Grid" />
                  </template>
                  <el-checkbox
                    v-model="checkAll"
                    :indeterminate="isIndeterminate"
                    @change="handleCheckAllChange"
                    >全选</el-checkbox
                  >
                  <el-checkbox-group
                    v-model="checkedCities"
                    class="columns-show-group"
                    @change="handleCheckedCitiesChange"
                  >
                    <el-checkbox
                      v-for="item in defaultColums.data"
                      :key="item.prop"
                      :label="item.prop"
                      >{{ item.label }}</el-checkbox
                    >
                  </el-checkbox-group>
                </el-popover>
              </el-button-group>
            </div>
          </div>
          <div class="flex">
            <div class="role w-full">
              <div v-loading="loading" class="w-full mt-[10px]">
                <el-table
                  ref="multipleTableRef"
                  :data="tableData.data"
                  style="width: 100%"
                  row-key="id"
                >
                  <el-table-column type="expand">
                    <template #default="props">
                      <el-form
                        label-position="left"
                        :inline="false"
                        class="demo-table-expand"
                      >
                        <el-form-item label="请求方法">
                          <span>{{ props.row.method }}</span>
                        </el-form-item>
                        <el-form-item label="请求参数">
                          <span>{{ props.row.params }}</span>
                        </el-form-item>
                      </el-form>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-for="item in colums.data"
                    :key="item.prop"
                    :prop="item.prop"
                    :label="item.label"
                    :width="item.width"
                    :align="item.align"
                  >
                    <template v-if="item.prop === 'time'" #default="scope">
                      <el-tag v-if="scope.row.time <= 300"
                        >{{ scope.row.time }}ms</el-tag
                      >
                      <el-tag v-else-if="scope.row.time <= 1000" type="warning"
                        >{{ scope.row.time }}ms</el-tag
                      >
                      <el-tag v-else type="danger"
                        >{{ scope.row.time }}ms</el-tag
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <div class="page w-full mt-[10px]">
                <el-pagination
                  v-model:current-page="pageObj.data.currentPage"
                  v-model:page-size="pageObj.data.pageSize"
                  :page-sizes="[10, 20, 30, 40, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="pageObj.data.total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import {
  Delete,
  Download,
  Grid,
  RefreshLeft,
  Search
} from "@element-plus/icons-vue";
import { ElForm, ElMessageBox, ElNotification, ElTable } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import { downloadFile } from "@/utils";
import { delLogsList, exportLogsList, getLogsList } from "@/api/monitorLogs";
const queryShow = ref(true);
const queryForm = reactive({
  data: {
    blurry: undefined,
    createTime: []
  }
});
const resetQuery = () => {
  queryForm.data = {
    blurry: undefined,
    createTime: []
  };
};
const search = async () => {
  pageObj.data.currentPage = 1;
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const getList = async () => {
  let { content, totalElements } = await getData();
  pageObj.data.total = totalElements;
  tableData.data = content;
};
const exportData = async () => {
  let res = await exportLogsList({
    current: pageObj.data.currentPage,
    size: pageObj.data.pageSize,
    sort: "id,desc",
    blurry: queryForm.data.blurry ? queryForm.data.blurry : undefined,
    createTime: queryForm.data.createTime.length
      ? queryForm.data.createTime
      : undefined
  });
  downloadFile(res, "操作日志数据", "xlsx");
};
const handleSizeChange = () => {
  search();
};
const handleCurrentChange = async () => {
  getList();
};
const getData = () => {
  loading.value = true;
  return new Promise<any>(async (resolve, reject) => {
    let data = await getLogsList({
      current: pageObj.data.currentPage,
      size: pageObj.data.pageSize,
      sort: "id,desc",
      blurry: queryForm.data.blurry ? queryForm.data.blurry : undefined,
      createTime: queryForm.data.createTime.length
        ? queryForm.data.createTime
        : undefined
    });
    loading.value = false;
    resolve(data);
  });
};
const tableData = reactive({
  data: []
});
const colums = reactive({
  data: [
    {
      label: "用户名",
      prop: "username"
    },
    {
      label: "IP",
      prop: "requestIp"
    },
    {
      label: "IP来源",
      prop: "address"
    },
    {
      label: "描述",
      prop: "description"
    },
    {
      label: "浏览器",
      prop: "browser"
    },
    {
      label: "请求耗时",
      prop: "time",
      align: "center"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const defaultColums = reactive({
  data: [
    {
      label: "用户名",
      prop: "username"
    },
    {
      label: "IP",
      prop: "requestIp"
    },
    {
      label: "IP来源",
      prop: "address"
    },
    {
      label: "描述",
      prop: "description"
    },
    {
      label: "浏览器",
      prop: "browser"
    },
    {
      label: "请求耗时",
      prop: "time",
      align: "center"
    },
    {
      label: "创建日期",
      prop: "createTime",
      width: "200px"
    }
  ]
});
const loading = ref(false);
const checkAll = ref(true);
const isIndeterminate = ref(false);
const checkedCities = ref([]);

const handleCheckAllChange = (val: boolean) => {
  checkedCities.value = val ? defaultColums.data.map(item => item.prop) : [];
  isIndeterminate.value = false;
  if (checkedCities.value.length) {
    colums.data = defaultColums.data;
  } else {
    colums.data = [];
  }
};
const pageObj = reactive({
  data: {
    currentPage: 1,
    pageSize: 10,
    total: 0
  }
});
const handleCheckedCitiesChange = (value: string[]) => {
  const checkedCount = value.length;
  checkAll.value = checkedCount === defaultColums.data.length;
  isIndeterminate.value =
    checkedCount > 0 && checkedCount < defaultColums.data.length;
  let cols = [];
  defaultColums.data.forEach(i => {
    if (value.indexOf(i.prop) > -1) {
      cols.push(i);
    }
  });
  colums.data = cols;
};
onMounted(() => {
  search();
  checkedCities.value = colums.data.map(item => item.prop);
});

const delSelect = async () => {
  ElMessageBox.confirm(`确认清空所有操作日志吗?`, "系统提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    dangerouslyUseHTMLString: true,
    draggable: true
  }).then(async () => {
    await delLogsList();
    ElNotification({
      title: "系统提示",
      message: "清空成功",
      type: "success"
    });
    search();
  });
};
</script>

<style scoped lang="scss">
:deep(.el-dropdown-menu__item i) {
  margin: 0;
}

:deep(.el-button:focus-visible) {
  outline: none;
}

.main-content {
  margin: 24px 24px 0 !important;
}

.search-form {
  :deep(.el-form-item) {
    margin-right: 4px;
    margin-bottom: 0;
  }
}

:deep(.el-card__body) {
  width: 100%;
}
</style>
